import 'package:flutter/material.dart';
import 'package:flutter_widgets/flutter_widgets.dart';

import 'styles.dart';

class SearchSample extends StatefulWidget {
  static const routeName = 'search';

  @override
  State<SearchSample> createState() => _SearchSampleState();
}

class _SearchSampleState extends State<SearchSample> {
  late _UserSearchDelegate _userSearchDelegate;

  @override
  void initState() {
    super.initState();
    _userSearchDelegate = _UserSearchDelegate(_onSearch);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const CommonAppBar(
        titleData: SearchSample.routeName,
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            showCustomSearch(context: context, delegate: _userSearchDelegate);
          },
          child: const Text('search'),
        ),
      ),
    );
  }

  Future _onSearch() {
    return Future.delayed(const Duration(seconds: 1));
  }
}

class _UserSearchDelegate extends CustomSearchDelegate {
  final Future Function() search;
  final historySearch = ['a', 'b'];
  final data = ['Anna', 'Bob', 'David'];

  var searchResult = ['Angel', 'Anna', 'Bob'];

  _UserSearchDelegate(this.search);

  @override
  String get searchFieldLabel => '支持模糊搜索';

  @override
  ThemeData appBarTheme(BuildContext context) {
    final theme = Theme.of(context);
    var outlineInputBorder = OutlineInputBorder(
      borderRadius: BorderRadius.circular(30),
      borderSide: const BorderSide(style: BorderStyle.none),
    );
    return super
        .appBarTheme(context)
        .copyWith(
          textTheme: theme.textTheme.copyWith(
            titleLarge: Styles.bodyText,
          ),
        )
        .copyWith(
          inputDecorationTheme: InputDecorationTheme(
            fillColor: Colors.black.withOpacity(0.08),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 8,
            ),
            focusedBorder: outlineInputBorder,
            filled: true,
            isDense: true,
            enabledBorder: outlineInputBorder,
            border: outlineInputBorder,
            hintStyle: Styles.bodyTextHint,
          ),
        );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return query.isEmpty
        ? _buildHistory(historySearch)
        : _buildListView(data.where((item) => item.contains(query)).toList());
  }

  ListView _buildHistory(List<String> suggestions) {
    return ListView.builder(
      itemCount: suggestions.length,
      itemBuilder: (BuildContext context, int i) {
        final suggestion = suggestions[i];
        return ListTile(
          leading: const Icon(Icons.history),
          title: HighlightedText(text: suggestion, highlight: query),
          onTap: () {
            query = suggestion;
            _onSearch(context);
          },
        );
      },
    );
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [CommonFlatButton(text: '搜索', onPressed: () => _onSearch(context))];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return appbarLeading(
        context: context,
        onPressed: () {
          close(context, null);
        });
  }

  @override
  Widget buildResults(BuildContext context) {
    return _buildListView(searchResult);
  }

  ListView _buildListView(List<String> list) {
    return ListView.separated(
      separatorBuilder: (context, index) => const Divider(),
      itemBuilder: (context, index) {
        return ListTile(
          title: HighlightedText(
            text: list[index],
            highlight: query,
          ),
        );
      },
      itemCount: list.length,
    );
  }

  void _onSearch(BuildContext context) async {
    await search();
    showResults(context);
  }
}
